# Skripta ki skrbi za povezavo s PRISOM
import sys
import System
import System.Threading
import clr
import time
import threading
import thread
import ee3
import ee3_gui

clr.AddReference('System')
clr.AddReference('System.Windows.Forms')
from System.ComponentModel import BackgroundWorker
clr.AddReference('System.Data')
from System.Data.SqlClient import SqlConnection
from System.Collections import *
from System.Threading import *

# FUNKCIJE
stevec_poizvedb = 0
class ObjectLocker(object):
      def __init__(self, obj):
              self.obj = obj
      def __enter__(self):
              global stevec_poizvedb
              stevec_poizvedb += 1
              Monitor.Enter(self.obj)
      def __exit__(self, *args):
              global stevec_poizvedb
              stevec_poizvedb -= 1
              Monitor.Exit(self.obj)

#
# POVEZAVA Z PRIS
#
conStrPris = 'Data Source=vmie3;initial catalog=KAKOVOST;user id=uporabnik;password=uporabnik; Connect Timeout=30'
def poizvedbaPRIS(stavek, izhod):
    dbPris = SqlConnection(conStrPris)
    l = ArrayList()
    i = 0
    print("PRIS: %s" %stavek)
    with ObjectLocker(dbPris):
        ee3_gui.barva_obrazca('Blue')
        while dbPris.State.ToString() != System.Data.ConnectionState.Open.ToString():
            try:
                dbPris.Open()
                cmd = dbPris.CreateCommand()
                cmd.CommandText = stavek
                r = cmd.ExecuteReader ()
                l = ArrayList()
                while r.Read ():
                    vrednost = izhod
                    for x in range(r.FieldCount):
                        vrednost = vrednost.replace("{%s}" %r.GetName(x) ,r[x].ToString())
                    l.Add(vrednost)
                r.Close ()
                ee3_gui.barva_obrazca('None')
            except Exception as e:
                ee3.debug.TraceDbg("Povezava na PRIS neuspesna!", "Stavek: %s\n%s" %(stavek, e.message.ToString()), "Warning")
                System.Threading.Thread.Sleep(1000)
                if (i<2):
                    ee3_gui.barva_obrazca('Orange')
                else:
                    ee3_gui.barva_obrazca('Red')
                i=i+1
        dbPris.Close ()
        return l

def bg_Poizvedba_PRIS(sender, args):
    tmp = poizvedbaPRIS(args.Argument[0], args.Argument[1])
    args.Result = [tmp, args.Argument[2], args.Argument[1]]

###################################

def dopolni(combobox, stavek, struktura, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_dopolni_completed
    if (combobox.GetType().Name == 'ComboBox'):
        combobox.ItemsSource = None
    elif (combobox.GetType().Name == 'TextBox'):
        combobox.Text = ''
   # obrazec.label_status.Content = opis
    worker.RunWorkerAsync([stavek, struktura, combobox])

def bg_dopolni_completed(sender, args):
   # obrazec.label_status.Content = ''
    if (args.Result[1].GetType().Name == 'ComboBox'):
        args.Result[1].ItemsSource = args.Result[0]
    elif (args.Result[1].GetType().Name == 'TextBox'):
        args.Result[1].Text = args.Result[0][0].ToString()

#################################

def bg_vpisi_completed(sender, args):
    args.Result[1][0].id = args.Result[0][0]
    args.Result[1][0].status = args.Result[1][1]
    args.Result[1][0].ok += "Plosca vpisana kot %s, ID=%s\n" %(args.Result[1][0].status, args.Result[1][0].id.ToString())
    args.Result[1][0].osvezi_znake()
    args.Result[1][0].konec_testa()


def vpisi(plosca, stavek, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_vpisi_completed
    worker.RunWorkerAsync([stavek, "{}", [plosca, opis]])


#################################

def kolicine(postavke, stavek, struktura, opis):
    worker = BackgroundWorker()
    worker.DoWork += bg_Poizvedba_PRIS
    worker.RunWorkerCompleted += bg_kolicine_completed
    postavke[0].Content = "n/a"
    postavke[1].Content = "n/a"
    postavke[2].Content = "n/a"
    postavke[3].Content = "n/a"
   # obrazec.label_status.Content = opis
    worker.RunWorkerAsync([stavek, struktura, postavke])

def bg_kolicine_completed(sender, args):
   # obrazec.label_status.Content = ''
   rezultat = args.Result[0][0].ToString().Split(';')
   if (rezultat[0] == ''):
       rezultat[0] = "0"
   args.Result[1][0].Content = rezultat[0]  #NALOG
   args.Result[1][1].Content = rezultat[1]  #PASS
   args.Result[1][2].Content = rezultat[2]  #FAIL
   args.Result[1][3].Content = rezultat[3]  #KARAN
   args.Result[1][4].Content = int(rezultat[0].ToString()) - int(rezultat[1].ToString()) - int(rezultat[2].ToString()) - int(rezultat[3].ToString())    #TODO
   #TODO = NALOG - PASS - FAIL - KARAN


#################################

def bg_stevilotestiranj_in_napake(sender, args):
    procesna = args.Argument[0].procesna
    operacija = args.Argument[1]
    stevilotestiranj = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s';" %(procesna,  operacija), "{}")[0])
    stevilotestiranjPASS = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' AND REZULTAT = 0;" %(procesna, operacija), "{}")[0])
    stevilotestiranjFAIL = int(poizvedbaPRIS("SELECT COUNT(*) FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' AND REZULTAT = 2;" %(procesna, operacija), "{}")[0])
    zadnjirezultat = poizvedbaPRIS("SELECT REZULTAT FROM SPREMNILISTREZULTAT WHERE ID = (SELECT TOP 1 REZULTAT FROM KAKOVOST.dbo.SPREMNILISTIZDELKA WHERE PROCESNA LIKE '%s%%' AND OPERACIJA = '%s' ORDER BY DATUM DESC);" %(procesna, operacija), "{REZULTAT}")
    napake_w = 0
    for napake in poizvedbaPRIS("SELECT ID, OPERACIJA, POZICIJA, NAPAKA FROM KAKOVOST.dbo.SPREMNILISTNAPAK WHERE PROCESNA = '%s';" %(procesna), "{ID},{OPERACIJA},{POZICIJA},{NAPAKA}"):
        napake_w+=1
        podatki = napake.Split(',')
        args.Argument[0].warning +='Napaka na operaciji %s: pozicija %s, napaka %s: %s\n' %(podatki[1], podatki[2], poizvedbaPRIS("SELECT NAPAK FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{NAPAK}")[0], poizvedbaPRIS("SELECT OPIS FROM KAKOVOST.dbo.SEZNAPAKN WHERE OLD='%s'" %podatki[3], "{OPIS}")[0])
    if (stevilotestiranj > 0):
        args.Argument[0].info += 'Plosca je ze bila %sx na tem testu! %sx PASS, %sx FAIL. \nZadnje stanje plosce je %s.\n' %(stevilotestiranj, stevilotestiranjPASS, stevilotestiranjFAIL, zadnjirezultat)
        
def bg_stevilotestiranj_in_napake_completed(sender, args):
    ee3.plosca.osvezi_znake()

def stevilotestiranj_in_napake(plosca, operacija):
    worker = BackgroundWorker()
    worker.DoWork += bg_stevilotestiranj_in_napake
    worker.RunWorkerCompleted += bg_stevilotestiranj_in_napake_completed
    worker.RunWorkerAsync([plosca, operacija])